﻿using System;
using System.Configuration;
using System.IO;
using System.Runtime.Remoting.Channels.Tcp;
using System.Runtime.Remoting.Channels;

namespace NabNetWeb
{
    public partial class _Record : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            string nabSerialNumber = Request.QueryString["sn"];
            if (!string.IsNullOrEmpty(nabSerialNumber))
            {
                string recordDirectory = ConfigurationManager.AppSettings["RecordDirectory"];
                if (!Path.IsPathRooted(recordDirectory))
                {
                    recordDirectory = Context.Server.MapPath(recordDirectory);
                }

                if (!Directory.Exists(recordDirectory))
                {
                    Directory.CreateDirectory(recordDirectory);
                }

                string fileName = nabSerialNumber + "_" + DateTime.Now.ToString("yyyyMMdd_HHmmss") + ".wav";
                fileName = Path.Combine(recordDirectory, fileName);

                using (FileStream fs = new FileStream(fileName, FileMode.Create))
                {
                    int length = (int) Request.InputStream.Length;
                    byte[] buffer = new byte[length];
                    Request.InputStream.Read(buffer, 0, length);
                    fs.Write(buffer, 0, length);
                }

                #region remoting call
                try
                {
                    TcpChannel channel = new TcpChannel();
                    if (ChannelServices.GetChannel(channel.ChannelName) == null)
                    {
                        ChannelServices.RegisterChannel(channel, false);
                    }
                    NabNetLib.Remoting.Interface.IRemoteNabNet remoteOperation = (NabNetLib.Remoting.Interface.IRemoteNabNet)Activator.GetObject(
                        typeof(NabNetLib.Remoting.Interface.IRemoteNabNet),
                        "tcp://localhost:1069/RemoteNabNet");

                    remoteOperation.RecordAction(nabSerialNumber, fileName);
                }
                catch (Exception ex)
                {
                    //todo log
                    string s = ex.ToString();
                }
                #endregion
            }
        }
    }
}
